package com.flca.frw.zk.comp;

import java.util.HashMap;
import java.util.Map;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Vbox;

import com.flca.frw.zk.helper.BaseDetailCtrl;
import com.flca.frw.zk.util.WindowBase;


public class DetailWindowCtrl extends WindowBase {

	private static final long serialVersionUID = 8238274055513196353L;

	private Object target;
	private String closeEventName;
	private String detailZulName;
	private BaseDetailCtrl detailCtrl;
	
	@SuppressWarnings("unchecked")
	public void setup(String aZulname, Object aTarget, String aEventName) 
	{
		detailZulName = aZulname;
		target = aTarget;
		closeEventName = aEventName;

		Map<String , Object> map = new HashMap<String, Object>();
		map.put("target", target);
		detailCtrl = (BaseDetailCtrl) Executions.createComponents(detailZulName, null, null);
		detailCtrl.setTarget(aTarget);
		
		Vbox vbox = (Vbox) getComponent("idDetailContent");
		vbox.getChildren().clear();
		detailCtrl.setParent(this);
		vbox.getChildren().add(detailCtrl);
		updateViewFromModel();
	}
	
	public void onCreate() 
	{
	}
	
	public void onSave() 
	{
		if (validate()) {
			updateModel();
			dispatchReadyForClose(true);
		}
	}

	public void onCancel() 
	{
		dispatchReadyForClose(false);
	}
	
	public boolean validate() 
	{
		return true;
	}
	
	@Override
	protected void updateModel() 
	{
		detailCtrl.updateModelFromView();
	}

	@Override
	protected void updateModelFromToView(boolean updateView) {
	}

	@Override
	protected void updateView() {
	}

	public void dispatchReadyForClose(boolean flag) 
	{
		if (!flag) {
			target = null;
		}
		Events.sendEvent(new Event(getCloseEventName(), this, target));
	}

	public Object getTarget() {
		return target;
	}

	public void setTarget(Object target) {
		this.target = target;
	}

	public String getCloseEventName() {
		return closeEventName;
	}

	public void setCloseEventName(String closeEventName) {
		this.closeEventName = closeEventName;
	}	
	
}
